package org.dromara.system.util.mxj;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 数据推送签名
 */
public class SignUtil {
    private static final Logger log = LoggerFactory.getLogger(SignUtil.class);

    /**
     * 签名
     * @param text 需要签名的字符串
     * @param salt 密钥
     * @param charset 字符编码
     * @return 签名
     */
    public static String sign(String text, String salt, String charset) {
        return DigestUtils.md5Hex(getBytes(text + salt, charset));
    }

    /**
     * 验签
     * @param text 需要签名的字符串
     * @param sign 签名
     * @param salt 密钥
     * @param charset 字符编码
     * @return 验签结果
     */
    public static boolean verify(String text, String salt, String charset, String sign) {
        String newSign = DigestUtils.md5Hex(getBytes(text + salt, charset));
        return newSign.equals(sign);
    }

    private static byte[] getBytes(String str, String charset) {
        if (StringUtils.isBlank(charset)) {
            return str.getBytes();
        }
        try {
            return str.getBytes(charset);
        } catch (Exception e) {
            throw new RuntimeException("异常"+e.getMessage());
        }
    }

    /**
     * map按key排序后拼接字符串
     * @param map
     * @return
     */
    public static String concatMapSortByKey(Map<String, Object> map) {
        StringBuilder sbd = new StringBuilder();
        if (map == null || map.isEmpty()) {
            return sbd.toString();
        }
        List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            Object val = map.get(key);
            if (val != null) {
                sbd.append(key).append("=").append(val).append("&");
            }
        }
        return sbd.toString();
    }

    public static void main(String[] args) {
        String salt = "Qwert12345&*";
        String jsonStr = "{\"data\":{\"mercId\":\"8223070521107DF\",\"mercCity\":\"1000\",\"mercProv\":\"991000\",\"oldMercId\":\"810005970000001\",\"mercAddr\":\"军民路520号百佳通\",\"ccardFee\":\"0.6\",\"dcardFee\":\"0.6\",\"stlBnkCode\":\"105100000017\",\"cerNo\":\"410725****1219\",\"busType\":\"Merc\",\"posMerId\":\"100129214\",\"mercArea\":\"100015\",\"dcardMax\":\"20\",\"externalCustomerNo\":\"8223070521107DF\",\"mercNm\":\"巨家瀚坤美术品\",\"stlTyp\":\"D0\",\"addFlg\":\"5\",\"belongAgtId\":\"D23100100094408\",\"creTm\":\"20250428154742\",\"corpNm\":\"娄彦北\",\"qrFee\":\"0.48\",\"stlAcoNm\":\"娄彦北\",\"stlAcoNo\":\"6217********2822\",\"stlBnkNo\":\"105100002123\",\"cerBegDat\":\"20150911\",\"mobNo\":\"155****6537\",\"quicFee\":\"0\",\"mercTyp\":\"2\",\"activeCode\":\"777973115622\",\"cerEndDat\":\"20250911\",\"agtMercId\":\"D23100100094408\",\"ts\":\"20250723151055\"},\"sign\":\"ad9967d098cbc5f307e6173bd12be06c\",\"brand_tag\":\"tool\",\"send_url\":\"http:\\/\\/121.40.66.143:4330\\/system\\/trading\\/MXJ\\/tradingWaterAssemble\"}";
        Map<String,Object> map = JSON.parseObject(jsonStr);
        Map<String,Object> data = (Map<String, Object>) map.get("data");
        String sign = MapUtils.getString(map, "sign");
        boolean verifyRst = verify(concatMapSortByKey(data), salt,"UTF-8", sign);
        log.info("verifyRst={}", verifyRst);
    }
}
